<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    发布订阅者模式
    1对多关系，多个观察者监听发布者
    添加观察者，移除观察者，通知观察者
    订阅者只管听，发布者只管做

    发布订阅者就是观察者的升级版

    jsdom事件就是观察者模式
    <script>
        class Publisher{
            
            constructor(){
                this.list={};
            }
            addSubscriber(key,fn){
                if(this.list[key]){
                    this.list[key].push(fn)
                }else{
                    this.list[key]=[fn]
                }
            }
            removeSubscriber(key){
                delete this.list[key]
            }
            notifySubscriber(key){
                if(key){
                    for (const fn of  this.list[key]) {
                            fn()
                        }
                   
                }else{
                    for (const subscriber in this.list) {
                        for (const fn of this.list[subscriber]) {
                            fn()
                        }
                    }
                }
            }
        }

        let a=new Publisher();
        a.addSubscriber('a',function(){
            console.log('我是订阅者1')
        })
        a.addSubscriber('b',function(){
            console.log('我是订阅者2')
        })
        a.notifySubscriber('b')
    </script>
</body>
</html>